package org.ttitfly.workflow.engine.basic.parser;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.ttitfly.workflow.engine.Process;
import org.ttitfly.workflow.exception.ProcessDefineException;
import org.ttitfly.workflow.factory.ObjectFactory;
import org.ttitfly.workflow.factory.ObjectNameUnavailableException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


/**
 * 基本的流程定义解释器
 * 
 * @author 潘海春
 * @version 2009-9-22
 */
public class BasicXMLProcessParser implements XMLProcessParser {

	/**
	 * 文档解释器
	 */
	private DocumentBuilder documentBuilder = null;
	{
		try {
			documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 对象工厂
	 */
	private ObjectFactory objectFactory;

	/**
	 * 默认的流程定义解释器
	 */
	private ProcessElementParser defaultParser = null;

	/**
	 * 构造函数
	 * 
	 * @param objectFactory
	 */
	public BasicXMLProcessParser(ObjectFactory objectFactory) {
		if (objectFactory == null) {
			throw new IllegalArgumentException("参数[objectFactory]不能为空！");
		}
		this.objectFactory = objectFactory;
		defaultParser = new BasicProcessElementParser(objectFactory);
	}

	@Override
	public Process parse(File file) throws ProcessDefineException {
		Document doc = null;
		try {
			doc = documentBuilder.parse(file);
		} catch (Exception e) {
			throw new ProcessDefineException(e);
		}
		Element processElement = doc.getDocumentElement();
		String parser = processElement.getAttribute("parser");
		if (parser == null || "".equals(parser)) {
			return defaultParser.parse(processElement);
		}
		try {
			return ((ProcessElementParser) objectFactory.getBean(parser)).parse(processElement);
		} catch (ObjectNameUnavailableException e) {
			throw new ProcessDefineException(e);
		}
	}

}
